package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.remark.RemarkClient;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.ReplyPageQuery;
import com.tianji.learning.domain.vo.ReplyVO;
import com.tianji.learning.enums.QuestionStatus;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.InteractionQuestionService;
import com.tianji.learning.service.InteractionReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author 蒼飞
 * @since 2023-09-04
 */
@Service
@RequiredArgsConstructor
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements InteractionReplyService {
    private final UserClient userClient;
    private final InteractionQuestionService interactionQuestionService;

    private final RemarkClient remarkClient;
    /**
     * 提交回答或评论
     * @param replyDTO
     */
    @Override
    public void addNewComment(ReplyDTO replyDTO) {
        //获取用户id
        Long userId = UserContext.getUser();
        //如果是回答就只需要问题id 回答内容 是否匿名 如果是评论则所有属性都需要
        InteractionReply reply = BeanUtils.copyBean(replyDTO, InteractionReply.class);
        reply.setUserId(userId);
        this.save(reply);
        boolean isAnswer = replyDTO.getAnswerId() == null;
        if (!isAnswer) {
            // 3.2.是评论，则需要更新上级回答的评论数量
            lambdaUpdate()
                    .setSql("reply_times = reply_times + 1")
                    .eq(InteractionReply::getId, replyDTO.getAnswerId())
                    .update();
        }
        // 3.3.尝试更新问题表中的状态、 最近一次回答、回答数量
        interactionQuestionService.lambdaUpdate()
                .set(isAnswer, InteractionQuestion::getLatestAnswerId, reply.getAnswerId())
                .setSql(isAnswer, "answer_times = answer_times + 1")
                .set(replyDTO.getIsStudent(), InteractionQuestion::getStatus, QuestionStatus.UN_CHECK.getValue())
                .eq(InteractionQuestion::getId, replyDTO.getQuestionId())
                .update();

        //todo 如果是学生 则增加积分
    }

    /**
     * 隐藏评论
     * @param id
     * @param hidden
     */
    @Override
    @Transactional
    public void hiddenReply(Long id, Boolean hidden) {
        // 1.查询
        InteractionReply old = getById(id);
        if (old == null) {
            return;
        }

        // 2.隐藏回答
        InteractionReply reply = new InteractionReply();
        reply.setId(id);
        reply.setHidden(hidden);
        updateById(reply);

        // 3.隐藏评论，先判断是否是回答，回答才需要隐藏下属评论
        if (old.getAnswerId() != null && old.getAnswerId() != 0) {
            // 3.1.有answerId，说明自己是评论，无需处理
            return;
        }
        // 3.2.没有answerId，说明自己是回答，需要隐藏回答下的评论
        lambdaUpdate()
                .set(InteractionReply::getHidden, hidden)
                .eq(InteractionReply::getAnswerId, id)
                .update();
    }

    /**
     * 分页查询回答和评论列表
     * @param replyPageQuery
     * @return
     */
    @Override
    public PageDTO<ReplyVO> queryComment(ReplyPageQuery replyPageQuery) {
        //replyPageQuery questionId不为空则代表查回答 answerId不为空则代表查评论
        //首先查回答列表
        Page<InteractionReply> page = new Page<>();
        if(replyPageQuery.getQuestionId() != null){
            page = this.lambdaQuery()
                    .eq(InteractionReply::getQuestionId, replyPageQuery.getQuestionId())
                    .page(replyPageQuery.toMpPage("liked_times", false));
        }
        List<InteractionReply> records = page.getRecords();
        List<ReplyVO> list = new ArrayList<>();
        if(CollUtils.isNotEmpty(records)){
            //封装vo
            for(InteractionReply record:records){
                ReplyVO replyVO = BeanUtils.copyBean(record, ReplyVO.class);
                //封装回答人信息
                String username = null;
                String userIcon = null;
                //如果不是匿名
                if(!record.getAnonymity()){
                    //调用用户服务查询昵称和头像
                    UserDTO userDTO = userClient.queryUserById(record.getUserId());
                    if (userDTO!=null){
                        username = userDTO.getName();
                        userIcon = userDTO.getIcon();
                        //用户类型
                        replyVO.setUserType(userDTO.getType());
                    }
                }
                //如果是查询回答列表 多一个目标用户昵称字段
                if(replyPageQuery.getAnswerId() != null){
                    String targetUserName = null;
                    UserDTO userDTO = userClient.queryUserById(record.getTargetUserId());
                    if (userDTO != null){
                        targetUserName = userDTO.getName();
                    }
                    replyVO.setTargetUserName(targetUserName);
                }
                //查询是否点过赞喜欢过
                Long bizLikedOne = remarkClient.isBizLikedOne(record.getId());
                replyVO.setLiked(bizLikedOne != null);
                replyVO.setUserName(username);
                replyVO.setUserIcon(userIcon);
                list.add(replyVO);
            }
        }
        return PageDTO.of(page,list);
    }
}
